package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.mapper.PermissionMapper;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.util.UserContext;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sun.security.util.Password;

import javax.servlet.http.HttpSession;
import javax.swing.*;
import java.io.IOException;
import java.util.List;

/**
 * @Description: 登入处理器类
 * @Author: 伍家钰
 * @Date: 2020/7/12 20:11
 * @Version: 1.0
 */
@Controller
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private IEmployeeService employeeServiceImpl;

   /* @Autowired
    private PermissionMapper permissionMapper;*/

    /**
     * 使用HttpSession而不使用Model是因为model只在一次request请求中起作用
     */
    @RequestMapping("/login")
    @ResponseBody
    public JsonResult login(String username, String password, HttpSession session) {
        /*Employee employee = employeeServiceImpl.login(username, password);
        if(!employee.isStatus()){
            return new JsonResult(false,"你的账号被禁用");
        }
        UserContext.setCurrentUser(employee);
        // 登入时查询查询除了管理员之外的用户所有权限,并保存到session中提高性能,避免每次都向数据库查询
        if (!employee.isAdmin()) {
            List<String> employeeExpression = permissionMapper.selectForExpression(employee.getId());
            UserContext.setExperssions(employeeExpression);
        }*/
        try {
            // 1.获取subject主体
            Subject subject = SecurityUtils.getSubject();
            // 对用户输入的密码进行加密
            Md5Hash md5Hash = new Md5Hash(password, username, 3);
            // 2.把前端传过来的参数封装到令牌
            UsernamePasswordToken token = new UsernamePasswordToken(username, md5Hash.toString());
            // 3.使用shiro提供的api来实现登入
            subject.login(token);
            return new JsonResult();
        } catch (UnknownAccountException e) {
            return new JsonResult(false, "账号不存在");
        } catch (IncorrectCredentialsException e) {
            return new JsonResult(false, "密码错误");
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false, "登录异常，请联系管理员");
        }

    }

   /* @RequestMapping("/loginOut")
    public String loginOut(HttpSession session) {
        session.removeAttribute("EMPLOYEE_IN_SESSION");
        return "redirect:/login.html";
    }*/


    /**
     * @return
     * @throws IOException
     */
    @RequestMapping("/updatePwdInput")
    public String updatePwdInput() throws IOException {
        // 1.获取登入的用户
        // Employee currentUser = UserContext.getCurrentUser();
        Employee employee = UserContext.getEmployee();
        // 2.获取用户的密码
        String oldPassword = employee.getPassword();
        // 3.将用户密码存入共享用于回显
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        attrs.getRequest().getSession().setAttribute("oldPassword", oldPassword);
        // UserContext.getSession().setAttribute("oldPassword", oldPassword);
        return "common/updatePwd";
    }

    @RequestMapping("/updatePwd")
    @ResponseBody
    public JsonResult updatePwd(String newPassword) throws IOException {
        // 1.获取登入的用户
        Employee employee = UserContext.getEmployee();
        // 2.判断填入的新密码是否为空
        if (newPassword != null && newPassword.trim().length() != 0) {
            // 5.密码不为空,调用employeeMapper中的修改密码的方法
            try {
                employeeServiceImpl.updateForPassword(employee.getId(), newPassword);
               /* // 6.移除session登入的信息
                UserContext.getSession().removeAttribute(UserContext.EMPLOYEE_IN_SESSION);
                return new JsonResult(true, "修改成功请重新登入");*/
                // 修改成功注销登入
                SecurityUtils.getSubject().logout();
            } catch (Exception e) {
                return new JsonResult(false, "修改失败,请联系管理员!");
            }
        }
        return new JsonResult(false, "新密码不能为空!");
    }

    /**
     * 重置密码
     *
     * @param id
     * @return
     * @throws IOException
     */
    @RequestMapping("/resetInput")
    @ResponseBody
    public JsonResult resetInput(Long id) throws IOException {
        // 1.获取当前登入的用户,获取其用户名用于回显
        Employee employee = UserContext.getEmployee();
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        attrs.getRequest().getSession().setAttribute("employee", employee);
        //Employee currentUser = UserContext.getCurrentUser();
        // 2.判断用户是否是管理员
        if (!employee.isAdmin()) {
            // 不是管理员则提示
            return new JsonResult(false, "你不是管理员,没有权限操作");
        }
        // 是管理员,则根据id查出用户信息
        Employee employee1 = employeeServiceImpl.selectById(id);
        attrs.getRequest().getSession().setAttribute("resetEmployee", employee);
        return new JsonResult();
    }

    @RequestMapping("/reset")
    public String reset() throws IOException {
        return "/common/resetPwd";
    }

    @RequestMapping("/resetPassword")
    @ResponseBody
    public JsonResult resetPwd(String newPassword, Long id) throws IOException {
        try {
            employeeServiceImpl.resetPassword(newPassword, id);
            return new JsonResult(true, "重置成功!");
        } catch (Exception e) {
            return new JsonResult(false, "重置失败!");
        }
    }
}
